package cn.yangphere.activity;

import java.text.DecimalFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class BmiNewActivity extends Activity{
	
	private Button button_calc;
	private EditText field_weight;
	private EditText field_height;
	private TextView view_result;
	private TextView view_suggest;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.main);
		
		findViews();
		setListener();
	}

	private void setListener() {
		button_calc.setOnClickListener(calcBMI);		
	}

	private void findViews() {
		button_calc = (Button)findViewById(R.id.submit);
		field_height = (EditText)findViewById(R.id.height);
		field_weight = (EditText)findViewById(R.id.weigth);
		view_result = (TextView)findViewById(R.id.result);
		view_suggest = (TextView)findViewById(R.id.suggest);
	}
	
	private OnClickListener calcBMI = new Button.OnClickListener(){
		public void onClick(View v) {
			try {
				String pattern = "0.00";
				DecimalFormat nf = new DecimalFormat(pattern);
				double height = Double
						.parseDouble(field_height.getText().toString()) / 100;
				double weight = Double
						.parseDouble(field_weight.getText().toString());
				double BMI = weight / (height * height);
				view_result.setText("Your BMI is " + nf.format(BMI));
				if(BMI > 25){
					view_suggest.setText(R.string.advice_heavy);
				}else if(BMI < 20){
					view_suggest.setText(R.string.advice_light);
				}else{
					view_suggest.setText(R.string.advice_average);
				}
				
				//openOptionsDialog();
				openToastDialog();
			} catch (NumberFormatException e) {
				Toast.makeText(BmiNewActivity.this, R.string.input_error, Toast.LENGTH_SHORT)
						.show();
			}
		}
	};

	protected void openOptionsDialog() {
		new AlertDialog.Builder(this)
						.setTitle(R.string.about_title)
						.setMessage(R.string.about_msg)
						.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface dialog,int which) {
								
							}
						})
						.show();
	}

	protected void openToastDialog() {
		Toast.makeText(this, R.string.txtBmi, Toast.LENGTH_SHORT).show();
	}
}
